<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>MybatisPlus | C·辰</title><meta name="author" content="辰"><meta name="copyright" content="辰"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="java">
<meta property="og:type" content="article">
<meta property="og:title" content="MybatisPlus">
<meta property="og:url" content="http://example.com/2023/06/02/MybatisPlus/index.html">
<meta property="og:site_name" content="C·辰">
<meta property="og:description" content="java">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/mybatisplus.svg">
<meta property="article:published_time" content="2023-06-02T14:22:22.000Z">
<meta property="article:modified_time" content="2023-09-10T05:54:04.672Z">
<meta property="article:author" content="辰">
<meta property="article:tag" content="MybatisPlus">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/mybatisplus.svg"><link rel="shortcut icon" href="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/Bell.ico"><link rel="canonical" href="http://example.com/2023/06/02/MybatisPlus/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'MybatisPlus',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-09-10 13:54:04'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog%2Fimages%2Favatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">32</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">10</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Demo</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/c2c_shop/"><i class="fa-fw fa fa-comments-o"></i><span> 商城</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/mybatisplus.svg')"><nav id="nav"><span id="blog-info"><a href="/" title="C·辰"><span class="site-name">C·辰</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Demo</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/c2c_shop/"><i class="fa-fw fa fa-comments-o"></i><span> 商城</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">MybatisPlus</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-06-02T14:22:22.000Z" title="发表于 2023-06-02 22:22:22">2023-06-02</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-09-10T05:54:04.672Z" title="更新于 2023-09-10 13:54:04">2023-09-10</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/java/">java</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>10分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="MybatisPlus"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="MyBatisPlus"><a href="#MyBatisPlus" class="headerlink" title="MyBatisPlus"></a>MyBatisPlus</h1><p><a target="_blank" rel="noopener" href="https://baomidou.com/">MyBatis-Plus</a></p>
<blockquote>
<p>默认</p>
<ul>
<li>雪花算法 – 主键</li>
<li>开启驼峰命名 – 映射</li>
</ul>
</blockquote>
<h1 id="依赖"><a href="#依赖" class="headerlink" title="依赖"></a>依赖</h1><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--数据库驱动--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>mysql<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mysql-connector-java<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>5.1.47<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--mybatis_plus--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.baomidou<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis-plus-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.4.2<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br/>

<br/>

<br/>

<br/>

<h1 id="快速开始"><a href="#快速开始" class="headerlink" title="快速开始"></a>快速开始</h1><h2 id="配置连接"><a href="#配置连接" class="headerlink" title="配置连接"></a>配置连接</h2><h2 id="mapper接口"><a href="#mapper接口" class="headerlink" title="mapper接口"></a>mapper接口</h2><ul>
<li>继承 <strong>BaseMapper&lt;泛型&gt;</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 在对应的Mapper 上面继承基本的类 BaseMapper</span></span><br><span class="line"></span><br><span class="line"><span class="meta">@Repository</span>   <span class="comment">//代表持久层</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">UserMapper</span> <span class="keyword">extends</span> <span class="title class_">BaseMapper</span>&lt;User&gt; &#123;</span><br><span class="line">    <span class="comment">// 所有的CRUD操作都已经编写完成了</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//查询全部用户</span></span><br><span class="line">List&lt;User&gt; users = userMapper.selectList(<span class="literal">null</span>);</span><br></pre></td></tr></table></figure>



<br/>

<br/>

<br/>

<br/>

<h1 id="配置日志"><a href="#配置日志" class="headerlink" title="配置日志"></a>配置日志</h1><figure class="highlight properties"><table><tr><td class="code"><pre><span class="line"><span class="comment">#默认日志</span></span><br><span class="line"><span class="attr">mybatis-plus.configuration.log-impl</span>=<span class="string">org.apache.ibatis.logging.stdout.StdOutImpl</span></span><br></pre></td></tr></table></figure>



<br/>

<br/>

<h1 id="注解"><a href="#注解" class="headerlink" title="注解"></a>注解</h1><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@TableField(select = false)</span>    <span class="comment">//查询时，则不返回该字段的值</span></span><br><span class="line"><span class="meta">@TableField(value = &quot;email&quot;)</span>    <span class="comment">//通过tableField进行字段不一致的映射</span></span><br><span class="line"><span class="meta">@TableField(exist = false)</span>  <span class="comment">//设置该字段在数据库表中不存在</span></span><br></pre></td></tr></table></figure>



<br/>

<br/>

<h1 id="CRUD拓展"><a href="#CRUD拓展" class="headerlink" title="CRUD拓展"></a>CRUD拓展</h1><ul>
<li><strong>T</strong>：<strong>泛型</strong></li>
</ul>
<h2 id="insert"><a href="#insert" class="headerlink" title="insert"></a>insert</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">int</span> <span class="variable">insert</span> <span class="operator">=</span> userMapper.insert(user);   <span class="comment">//自动生成id</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>数据库插入的id的默认值：<strong>全局的唯一id</strong></p>
</blockquote>
<br/>

<h2 id="主键生成策略"><a href="#主键生成策略" class="headerlink" title="主键生成策略"></a>主键生成策略</h2><blockquote>
<p>默认 ID_WORKER全局唯一id</p>
</blockquote>
<br/>

<p>1、方式一：默认<strong>雪花算法</strong></p>
<p>snowflake是Twitter开源的分布式lD生成算i法，结果是一s个long型的ID。其核心思想是：使用41bit作为毫秒数，10bit作为机器的is(5个bit是数据中心，5个bit的机器引D),12bit作为毫秒内的流水号（意味着每个节点在每毫秒可以产生4096个ID),最后还有一个符号位，永远是0。可以保证几乎全球<strong>唯一</strong>！</p>
<br/>

<p>2、方式二：<strong>注解配置规则</strong></p>
<blockquote>
<p><strong>主键自增</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">enum</span> <span class="title class_">IdType</span> &#123;</span><br><span class="line"> AUTO(<span class="number">0</span>),	<span class="comment">//数据库id自增</span></span><br><span class="line"> NONE(<span class="number">1</span>),	<span class="comment">//未设置主键</span></span><br><span class="line"> INPUT(<span class="number">2</span>),	<span class="comment">//手动输入</span></span><br><span class="line"> ID_WORKER_STR(<span class="number">3</span>),	<span class="comment">//字符串表示法</span></span><br><span class="line"> ASSIGN_UUID(<span class="number">4</span>)	<span class="comment">//全局唯一id uuid</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</blockquote>
<ul>
<li>实体类字段加注解：**@TableId(type &#x3D; IdType.策略)**   —  <strong>数据库对应的字段也必须要自增</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@TableId(type = IdType.AUTO)</span>	<span class="comment">//数据库id自增，不用配置输入</span></span><br><span class="line"><span class="keyword">private</span> Long id;</span><br><span class="line"></span><br><span class="line"> <span class="meta">@TableId(type = IdType.INPUT)</span>  <span class="comment">//设置为手动输入id，需要写入</span></span><br></pre></td></tr></table></figure>



<br/>

<br/>

<h2 id="update"><a href="#update" class="headerlink" title="update"></a>update</h2><ul>
<li>可动态判断当前的参数是否为null，!null-&gt;update</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//通过条件自动拼接动态sql</span></span><br><span class="line"><span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> userMapper.updateById(user);</span><br></pre></td></tr></table></figure>

<br/>

<h2 id="自动填充"><a href="#自动填充" class="headerlink" title="自动填充"></a>自动填充</h2><ul>
<li>创建时间、修改时间 （gmt_create  ,  gmt_modified）</li>
</ul>
<blockquote>
<p>方式一：<strong>数据库级别</strong></p>
</blockquote>
<p>1、新增  create_time 、 update_time</p>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230905191245003.png" alt="image-20230905191245003"></p>
<p>2、实体类同步</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//plus默认开启驼峰</span></span><br><span class="line"><span class="keyword">private</span> Date createTime;</span><br><span class="line"><span class="keyword">private</span> Date updateTime;</span><br></pre></td></tr></table></figure>

<p>3、数据库级别会对修改的数据的修改时间进行自动化更新</p>
<br/>

<br/>

<blockquote>
<p>方式二：<strong>代码级别</strong></p>
</blockquote>
<p>1、删除数据库的字段的默认值操作</p>
<p>2、实体类需要自动填充的字段上添加注解：**@TableField(fill &#x3D; FieldFill.何时填充)**</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//添加时自动填充内容</span></span><br><span class="line"><span class="meta">@TableField(fill = FieldFill.INSERT)</span></span><br><span class="line"><span class="keyword">private</span> LocalDateTime createTime;</span><br><span class="line"></span><br><span class="line"><span class="comment">//更新时自动填充内容</span></span><br><span class="line"><span class="meta">@TableField(fill = FieldFill.INSERT_UPDATE)</span></span><br><span class="line"><span class="keyword">private</span> LocalDateTime updateTime;</span><br></pre></td></tr></table></figure>

<br/>

<p>3、实现类</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MyMetaObjectHandler</span> <span class="keyword">implements</span> <span class="title class_">MetaObjectHandler</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//插入时的填充策略</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">insertFill</span><span class="params">(MetaObject metaObject)</span> &#123;</span><br><span class="line">        log.info(<span class="string">&quot;start insert fill......&quot;</span>);</span><br><span class="line">        <span class="built_in">this</span>.strictInsertFill(metaObject, <span class="string">&quot;createTime&quot;</span>, LocalDateTime.class, LocalDateTime.now());</span><br><span class="line">        <span class="built_in">this</span>.strictInsertFill(metaObject, <span class="string">&quot;updateTime&quot;</span>, LocalDateTime.class, LocalDateTime.now());</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//更新时的填充策略</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">updateFill</span><span class="params">(MetaObject metaObject)</span> &#123;</span><br><span class="line">        log.info(<span class="string">&quot;start update fill ....&quot;</span>);</span><br><span class="line">        <span class="built_in">this</span>.strictUpdateFill(metaObject, <span class="string">&quot;updateTime&quot;</span>, LocalDateTime.class, LocalDateTime.now()); <span class="comment">// 起始版本 3.3.0(推荐)</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<br/>

<h2 id="乐观锁"><a href="#乐观锁" class="headerlink" title="乐观锁"></a>乐观锁</h2><blockquote>
<p><strong>乐观锁</strong>：故名思意十分乐观，它总是认为不会出现问题，无论干什么不去上锁！如果出现了问题，再次更新值测试</p>
<p><strong>悲观锁</strong>：故名思意十分悲观，它总是认为总是出现问题，无论干什么都会上锁！再去操作！</p>
</blockquote>
<p>乐观锁实现方式：</p>
<ul>
<li><p>取出记录时，获取当前version</p>
</li>
<li><p>更新时，带上这个version</p>
</li>
<li><p>执行更新时，set version&#x3D;newVersion where version&#x3D;oldVersion</p>
</li>
<li><p>如果version不对，就更新失败</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">乐观锁：</span><br><span class="line"><span class="number">1</span>、先查询，获得版本号version=<span class="number">1</span></span><br><span class="line">--A</span><br><span class="line">update user <span class="type">set</span> <span class="variable">name</span> <span class="operator">=</span><span class="string">&quot;kuangshen&quot;</span>,version = version + <span class="number">1</span></span><br><span class="line"><span class="type">where</span> <span class="variable">id</span> <span class="operator">=</span> <span class="number">2</span> <span class="type">and</span> <span class="variable">version</span> <span class="operator">=</span> <span class="number">1</span></span><br><span class="line">     </span><br><span class="line">--B线程抢先完成，这个时候version=<span class="number">2</span>,会导致A修改失败！</span><br><span class="line">update user <span class="type">set</span> <span class="variable">name</span> <span class="operator">=</span><span class="string">&quot;kuangshen&quot;</span>,version = version + <span class="number">1</span></span><br><span class="line"><span class="type">where</span> <span class="variable">id</span> <span class="operator">=</span> <span class="number">2</span> <span class="type">and</span> <span class="variable">version</span> <span class="operator">=</span><span class="number">1</span></span><br></pre></td></tr></table></figure></li>
</ul>
<br/>

<blockquote>
<p>测试MybatisPlus乐观锁插件</p>
</blockquote>
<p>1、数据库表增加字段 <strong>version</strong></p>
<p>2、实体类对应的字段加注解 ： <strong>@Version</strong>    &#x2F;&#x2F;乐观锁注解</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Version</span>    <span class="comment">//乐观锁注解</span></span><br><span class="line"><span class="keyword">private</span> Integer version;</span><br></pre></td></tr></table></figure>

<br/>

<p>3、<strong>配置插件</strong></p>
<ul>
<li>拦截器配置类</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@MapperScan(&quot;com.chen.demo.mapper&quot;)</span></span><br><span class="line"><span class="meta">@EnableTransactionManagement</span>      <span class="comment">//自动管理事务</span></span><br><span class="line"><span class="meta">@Configuration</span>  <span class="comment">//配置类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MybatisPlusConfig</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//注册乐观锁插件</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> MybatisPlusInterceptor <span class="title function_">mybatisPlusInterceptor</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">MybatisPlusInterceptor</span> <span class="variable">interceptor</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">MybatisPlusInterceptor</span>();</span><br><span class="line">        interceptor.addInnerInterceptor(<span class="keyword">new</span> <span class="title class_">OptimisticLockerInnerInterceptor</span>());</span><br><span class="line">        <span class="keyword">return</span> interceptor;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<br/>

<p>4、Test</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//1、查询、修改</span></span><br><span class="line"><span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> userMapper.selectById(<span class="number">1L</span>);</span><br><span class="line">user.setAge(<span class="number">188888</span>);</span><br><span class="line"></span><br><span class="line"><span class="type">User</span> <span class="variable">user2</span> <span class="operator">=</span> userMapper.selectById(<span class="number">1L</span>);</span><br><span class="line">user2.setAge(<span class="number">28888888</span>);</span><br><span class="line"><span class="comment">//3、执行更新</span></span><br><span class="line">userMapper.updateById(user2);</span><br><span class="line"></span><br><span class="line">userMapper.updateById(user);   <span class="comment">//如果没有乐观锁就会覆盖插队线程的值</span></span><br></pre></td></tr></table></figure>

<br/>

<br/>



<h2 id="select"><a href="#select" class="headerlink" title="select"></a>select</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//查询全部用户</span></span><br><span class="line">List&lt;User&gt; users = userMapper.selectList(<span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//单个查询  -- selectById</span></span><br><span class="line"><span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> userMapper.selectById(<span class="number">1L</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//批量查询  -- selectBatchIds</span></span><br><span class="line">List&lt;User&gt; users = userMapper.selectBatchIds(Arrays.asList(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>));</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//按条件查询  -- selectByMap</span></span><br><span class="line">HashMap&lt;String, Object&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">map.put(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;辰&quot;</span>);	<span class="comment">//自定义查询条件</span></span><br><span class="line">List&lt;User&gt; users = userMapper.selectByMap(map);</span><br></pre></td></tr></table></figure>



<br/>

<br/>



<h2 id="分页查询"><a href="#分页查询" class="headerlink" title="分页查询"></a>分页查询</h2><p>1、拦截器配置类</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@MapperScan(&quot;com.chen.demo.mapper&quot;)</span></span><br><span class="line"><span class="meta">@EnableTransactionManagement</span>      <span class="comment">//自动管理事务</span></span><br><span class="line"><span class="meta">@Configuration</span>  <span class="comment">//配置类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MybatisPlusConfig</span> &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> MybatisPlusInterceptor <span class="title function_">mybatisPlusInterceptor</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">MybatisPlusInterceptor</span> <span class="variable">interceptor</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">MybatisPlusInterceptor</span>();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//注册乐观锁插件</span></span><br><span class="line">        interceptor.addInnerInterceptor(<span class="keyword">new</span> <span class="title class_">OptimisticLockerInnerInterceptor</span>());</span><br><span class="line"></span><br><span class="line">        <span class="comment">//分页插件</span></span><br><span class="line">        interceptor.addInnerInterceptor(<span class="keyword">new</span> <span class="title class_">PaginationInnerInterceptor</span>(DbType.MYSQL));</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> interceptor;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<p>2、使用</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//pageNo , pageSize</span></span><br><span class="line">Page&lt;User&gt; page = <span class="keyword">new</span> <span class="title class_">Page</span>&lt;&gt;(<span class="number">2</span>,<span class="number">2</span>);</span><br><span class="line">userMapper.selectPage(page,<span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">page.getPages(); <span class="comment">//一共多少页</span></span><br><span class="line">page.getTotal();<span class="comment">//一共多少条数据</span></span><br><span class="line">page.getCurrent(); <span class="comment">//当前第几页</span></span><br><span class="line">page.getRecords();<span class="comment">//获取分页后的数据</span></span><br></pre></td></tr></table></figure>



<br/>

<br/>

<h2 id="删除"><a href="#删除" class="headerlink" title="删除"></a>删除</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//单个删除  -- deleteById</span></span><br><span class="line">userMapper.deleteById(<span class="number">1L</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//批量删除  -- deleteBatchIds</span></span><br><span class="line">userMapper.deleteBatchIds(Arrays.asList(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>));</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//指定删除(动态) -- deleteByMap</span></span><br><span class="line">HashMap&lt;String, Object&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">map.put(<span class="string">&quot;email&quot;</span>,<span class="string">&quot;99999999999999@qq/com&quot;</span>);</span><br><span class="line">userMapper.deleteByMap(map);</span><br></pre></td></tr></table></figure>



<br/>

<br/>

<h2 id="逻辑删除"><a href="#逻辑删除" class="headerlink" title="逻辑删除"></a>逻辑删除</h2><blockquote>
<p>物理删除：从数据库中直接移除</p>
<p>逻辑删除：再数据库中没有被移除，而是通过一个变量来让他失效！deleted &#x3D; 0 &#x3D;&gt; deleted &#x3D; 1</p>
</blockquote>
<p>1、数据库表增加删除字段：deleted</p>
<p>2、实体类字段增加注解：**@TableLogic**  </p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@TableLogic</span>  <span class="comment">//逻辑删除</span></span><br><span class="line"><span class="keyword">private</span> Integer deleted;</span><br></pre></td></tr></table></figure>

<br/>

<p>3、配置插件</p>
<ul>
<li>配置文件</li>
</ul>
<figure class="highlight yaml"><table><tr><td class="code"><pre><span class="line"><span class="attr">mybatis-plus:</span></span><br><span class="line">  <span class="attr">global-config:</span></span><br><span class="line">    <span class="attr">db-config:</span></span><br><span class="line">      <span class="attr">logic-delete-field:</span> <span class="string">flag</span> <span class="comment"># 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)</span></span><br><span class="line">      <span class="attr">logic-delete-value:</span> <span class="number">1</span> <span class="comment"># 逻辑已删除值(默认为 1)</span></span><br><span class="line">      <span class="attr">logic-not-delete-value:</span> <span class="number">0</span> <span class="comment"># 逻辑未删除值(默认为 0)</span></span><br></pre></td></tr></table></figure>

<br/>

<p>4、使用</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">userMapper.deleteById(<span class="number">1</span>);</span><br></pre></td></tr></table></figure>

<blockquote>
<p><strong>本质上执行更新操作，把标记为删除的字段更改而已</strong></p>
<p>查询的时候，会增加判断是否删除条件</p>
</blockquote>
<br/>

<br/>

<br/>

<br/>

<h1 id="条件构造器【-】"><a href="#条件构造器【-】" class="headerlink" title="条件构造器【*】"></a>条件构造器【*】</h1><ul>
<li><h2 id="QueryWrapper"><a href="#QueryWrapper" class="headerlink" title="QueryWrapper"></a><strong>QueryWrapper</strong></h2></li>
<li><p>编写查询条件</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//查询name不为空，且邮箱不为空，	 --  isNotNull</span></span><br><span class="line"><span class="comment">//年龄大于等于18的用户  -- ge</span></span><br><span class="line">QueryWrapper&lt;User&gt; wrapper = <span class="keyword">new</span> <span class="title class_">QueryWrapper</span>&lt;&gt;();</span><br><span class="line">wrapper</span><br><span class="line">        .isNotNull(<span class="string">&quot;name&quot;</span>)</span><br><span class="line">        .isNotNull(<span class="string">&quot;email&quot;</span>)</span><br><span class="line">        .ge(<span class="string">&quot;age&quot;</span>,<span class="number">12</span>);</span><br><span class="line">userMapper.selectList(wrapper);<span class="comment">//列表</span></span><br></pre></td></tr></table></figure>

<br/>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//字符判断  -- eq  </span></span><br><span class="line">QueryWrapper&lt;User&gt; wrapper = <span class="keyword">new</span> <span class="title class_">QueryWrapper</span>&lt;&gt;();</span><br><span class="line">wrapper.eq(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;辰&quot;</span>);</span><br><span class="line">userMapper.selectOne(wrapper);<span class="comment">//单一</span></span><br></pre></td></tr></table></figure>

<br/>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//查询指定年龄 区间  -- between</span></span><br><span class="line">QueryWrapper&lt;User&gt; wrapper = <span class="keyword">new</span> <span class="title class_">QueryWrapper</span>&lt;&gt;();</span><br><span class="line">wrapper.between(<span class="string">&quot;age&quot;</span>,<span class="number">1</span>,<span class="number">7</span>);</span><br><span class="line"> <span class="type">Integer</span> <span class="variable">integer</span> <span class="operator">=</span> userMapper.selectCount(wrapper);<span class="comment">//总数</span></span><br></pre></td></tr></table></figure>

<br/>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//模糊查询  -- notLike不包含  -- likeLeft包含字符&amp;通配符位置</span></span><br><span class="line">QueryWrapper&lt;User&gt; wrapper = <span class="keyword">new</span> <span class="title class_">QueryWrapper</span>&lt;&gt;();</span><br><span class="line"><span class="comment">//  左/右 --&gt; 通配符的位置  %c%</span></span><br><span class="line">wrapper</span><br><span class="line">        .notLike(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;c&quot;</span>)</span><br><span class="line">        .likeLeft(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;辰&quot;</span>);</span><br><span class="line"></span><br><span class="line">List&lt;Map&lt;String, Object&gt;&gt; maps = userMapper.selectMaps(wrapper);</span><br><span class="line">maps.forEach(System.out::println);</span><br></pre></td></tr></table></figure>

<br/>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//通过id进行排序  -- orderByDesc</span></span><br><span class="line">QueryWrapper&lt;User&gt; wrapper = <span class="keyword">new</span> <span class="title class_">QueryWrapper</span>&lt;&gt;();</span><br><span class="line"></span><br><span class="line">wrapper.orderByDesc(<span class="string">&quot;id&quot;</span>);</span><br><span class="line"></span><br><span class="line">List&lt;User&gt; users = userMapper.selectList(wrapper);</span><br><span class="line">users.forEach(System.out::println);</span><br></pre></td></tr></table></figure>

<br/>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//连接查询</span></span><br><span class="line">QueryWrapper&lt;User&gt; wrapper = <span class="keyword">new</span> <span class="title class_">QueryWrapper</span>&lt;&gt;();</span><br><span class="line"></span><br><span class="line"><span class="comment">//id 在子查询中查询出来的</span></span><br><span class="line">wrapper.inSql(<span class="string">&quot;id&quot;</span>,<span class="string">&quot;select id from user where id &lt; 3&quot;</span>);</span><br><span class="line"></span><br><span class="line">List&lt;Object&gt; objects = userMapper.selectObjs(wrapper);</span><br><span class="line">objects.forEach(System.out::println);</span><br></pre></td></tr></table></figure>



<br/>

<ul>
<li><h2 id="lambdaQuery"><a href="#lambdaQuery" class="headerlink" title="lambdaQuery"></a>lambdaQuery</h2></li>
</ul>
<p>通过方法引用的方式来使用实体字段名的操作,不需要手动写字段名防止写错</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//  Wrappers.&lt;实体&gt;lambdaQuery()</span></span><br><span class="line">LambdaQueryWrapper&lt;User&gt; lambda3 = Wrappers.&lt;User&gt;lambdaQuery();</span><br><span class="line">lambda3.like(User::getName, <span class="string">&quot;雨&quot;</span>).lt(User::getAge, <span class="number">40</span>);</span><br><span class="line">List&lt;User&gt; users = userMapper.selectList(lambda3);</span><br></pre></td></tr></table></figure>



<br/>

<br/>

<br/>

<h1 id="代码生成器"><a href="#代码生成器" class="headerlink" title="代码生成器"></a>代码生成器</h1><ul>
<li>依赖</li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.baomidou<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis-plus-generator<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.5.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br/>

<br/>

<ul>
<li>只需要改实体类名字 和包名 还有 数据库配置即可</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 代码自动生成器</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">CCode</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">// 需要构建一个 代码自动生成器 对象</span></span><br><span class="line">        <span class="type">AutoGenerator</span> <span class="variable">mpg</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">AutoGenerator</span>();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 配置策略</span></span><br><span class="line">        <span class="comment">// 1、全局配置</span></span><br><span class="line">        <span class="type">GlobalConfig</span> <span class="variable">gc</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">GlobalConfig</span>();</span><br><span class="line">        <span class="type">String</span> <span class="variable">projectPath</span> <span class="operator">=</span> System.getProperty(<span class="string">&quot;user.dir&quot;</span>);</span><br><span class="line">        gc.setOutputDir(projectPath+<span class="string">&quot;/src/main/java&quot;</span>);</span><br><span class="line">        gc.setAuthor(<span class="string">&quot;ccc&quot;</span>); gc.setOpen(<span class="literal">false</span>);</span><br><span class="line">        gc.setFileOverride(<span class="literal">false</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 是否覆盖</span></span><br><span class="line">        gc.setServiceName(<span class="string">&quot;%sService&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 去Service的I前缀</span></span><br><span class="line">        gc.setIdType(IdType.ID_WORKER);</span><br><span class="line">        gc.setDateType(DateType.ONLY_DATE);</span><br><span class="line">        gc.setSwagger2(<span class="literal">true</span>);</span><br><span class="line">        mpg.setGlobalConfig(gc);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//2、设置数据源</span></span><br><span class="line">        <span class="type">DataSourceConfig</span> <span class="variable">dsc</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DataSourceConfig</span>();</span><br><span class="line">        dsc.setUrl(<span class="string">&quot;jdbc:mysql://localhost:3306/kuang_community? useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=GMT%2B8&quot;</span>);</span><br><span class="line">        dsc.setDriverName(<span class="string">&quot;com.mysql.cj.jdbc.Driver&quot;</span>);</span><br><span class="line">        dsc.setUsername(<span class="string">&quot;root&quot;</span>);</span><br><span class="line">        dsc.setPassword(<span class="string">&quot;123456&quot;</span>);</span><br><span class="line">        dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//3、包的配置</span></span><br><span class="line">        <span class="type">PackageConfig</span> <span class="variable">pc</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">PackageConfig</span>();</span><br><span class="line">        <span class="comment">//只需要改实体类名字 和包名 还有 数据库配置即可</span></span><br><span class="line">        pc.setModuleName(<span class="string">&quot;blog&quot;</span>); pc.setParent(<span class="string">&quot;com.kuang&quot;</span>);</span><br><span class="line">        pc.setEntity(<span class="string">&quot;entity&quot;</span>); pc.setMapper(<span class="string">&quot;mapper&quot;</span>);</span><br><span class="line">        pc.setService(<span class="string">&quot;service&quot;</span>); pc.setController(<span class="string">&quot;controller&quot;</span>);</span><br><span class="line">        mpg.setPackageInfo(pc);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//4、策略配置</span></span><br><span class="line">        <span class="type">StrategyConfig</span> <span class="variable">strategy</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">StrategyConfig</span>();</span><br><span class="line">        strategy.setInclude(<span class="string">&quot;blog_tags&quot;</span>,<span class="string">&quot;course&quot;</span>,<span class="string">&quot;links&quot;</span>,<span class="string">&quot;sys_settings&quot;</span>,<span class="string">&quot;user_record&quot;</span>,<span class="string">&quot; user_say&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 设置要映射的表名</span></span><br><span class="line">        strategy.setNaming(NamingStrategy.underline_to_camel);</span><br><span class="line">        strategy.setColumnNaming(NamingStrategy.underline_to_camel);</span><br><span class="line">        strategy.setEntityLombokModel(<span class="literal">true</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 自动lombok；</span></span><br><span class="line">        strategy.setLogicDeleteFieldName(<span class="string">&quot;deleted&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 自动填充配置</span></span><br><span class="line">        <span class="type">TableFill</span> <span class="variable">gmtCreate</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TableFill</span>(<span class="string">&quot;gmt_create&quot;</span>, FieldFill.INSERT);</span><br><span class="line">        <span class="type">TableFill</span> <span class="variable">gmtModified</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TableFill</span>(<span class="string">&quot;gmt_modified&quot;</span>, FieldFill.INSERT_UPDATE);</span><br><span class="line">        ArrayList&lt;TableFill&gt; tableFills = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line">        tableFills.add(gmtCreate); tableFills.add(gmtModified);</span><br><span class="line">        strategy.setTableFillList(tableFills);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 乐观锁</span></span><br><span class="line">        strategy.setVersionFieldName(<span class="string">&quot;version&quot;</span>);</span><br><span class="line">        strategy.setRestControllerStyle(<span class="literal">true</span>);</span><br><span class="line">        strategy.setControllerMappingHyphenStyle(<span class="literal">true</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// localhost:8080/hello_id_2</span></span><br><span class="line">        mpg.setStrategy(strategy);</span><br><span class="line">        mpg.execute(); <span class="comment">//执行</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://example.com">辰</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2023/06/02/MybatisPlus/">http://example.com/2023/06/02/MybatisPlus/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">C·辰</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/MybatisPlus/">MybatisPlus</a></div><div class="post_share"><div class="social-share" data-image="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/mybatisplus.svg" data-sites="wechat,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/05/05/Linux/" title="Linux"><img class="cover" src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/Linux.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Linux</div></div></a></div><div class="next-post pull-right"><a href="/2023/07/06/%E5%90%8E%E7%AB%AF%E8%A7%84%E5%88%92/" title="Java后端"><img class="cover" src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/javahd.jpeg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Java后端</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog%2Fimages%2Favatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">辰</div><div class="author-info__description">车遥马慢</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">32</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">10</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/hchenp"><i class="fab fa-github"></i><span>Gitee-HchenP</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/hchenp" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://github.com/Pxlchen?tab=projects" target="_blank" title="CSDN"><i class="fa fa-book-open"></i></a><a class="social-icon" href="https://console.cloud.tencent.com/cos/bucket?bucket=chen-1317386995&amp;region=ap-guangzhou&amp;isPublic=true" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="mailto:1107383160@qq.com" target="_blank" title="Email"><i class="fas fa-envelope-open-text"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">C2C-Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#MyBatisPlus"><span class="toc-number">1.</span> <span class="toc-text">MyBatisPlus</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BE%9D%E8%B5%96"><span class="toc-number">2.</span> <span class="toc-text">依赖</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B"><span class="toc-number">3.</span> <span class="toc-text">快速开始</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%85%8D%E7%BD%AE%E8%BF%9E%E6%8E%A5"><span class="toc-number">3.1.</span> <span class="toc-text">配置连接</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#mapper%E6%8E%A5%E5%8F%A3"><span class="toc-number">3.2.</span> <span class="toc-text">mapper接口</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8"><span class="toc-number">3.3.</span> <span class="toc-text">使用</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E9%85%8D%E7%BD%AE%E6%97%A5%E5%BF%97"><span class="toc-number">4.</span> <span class="toc-text">配置日志</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%B3%A8%E8%A7%A3"><span class="toc-number">5.</span> <span class="toc-text">注解</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#CRUD%E6%8B%93%E5%B1%95"><span class="toc-number">6.</span> <span class="toc-text">CRUD拓展</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#insert"><span class="toc-number">6.1.</span> <span class="toc-text">insert</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%BB%E9%94%AE%E7%94%9F%E6%88%90%E7%AD%96%E7%95%A5"><span class="toc-number">6.2.</span> <span class="toc-text">主键生成策略</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#update"><span class="toc-number">6.3.</span> <span class="toc-text">update</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%87%AA%E5%8A%A8%E5%A1%AB%E5%85%85"><span class="toc-number">6.4.</span> <span class="toc-text">自动填充</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B9%90%E8%A7%82%E9%94%81"><span class="toc-number">6.5.</span> <span class="toc-text">乐观锁</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#select"><span class="toc-number">6.6.</span> <span class="toc-text">select</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%86%E9%A1%B5%E6%9F%A5%E8%AF%A2"><span class="toc-number">6.7.</span> <span class="toc-text">分页查询</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%A0%E9%99%A4"><span class="toc-number">6.8.</span> <span class="toc-text">删除</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%80%BB%E8%BE%91%E5%88%A0%E9%99%A4"><span class="toc-number">6.9.</span> <span class="toc-text">逻辑删除</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%9D%A1%E4%BB%B6%E6%9E%84%E9%80%A0%E5%99%A8%E3%80%90-%E3%80%91"><span class="toc-number">7.</span> <span class="toc-text">条件构造器【*】</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#QueryWrapper"><span class="toc-number">7.1.</span> <span class="toc-text">QueryWrapper</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#lambdaQuery"><span class="toc-number">7.2.</span> <span class="toc-text">lambdaQuery</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E7%94%9F%E6%88%90%E5%99%A8"><span class="toc-number">8.</span> <span class="toc-text">代码生成器</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/07/06/Java%E5%85%AB%E8%82%A1%E6%96%87/" title="Java八股文"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/javaall.gif" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java八股文"/></a><div class="content"><a class="title" href="/2023/07/06/Java%E5%85%AB%E8%82%A1%E6%96%87/" title="Java八股文">Java八股文</a><time datetime="2023-07-06T14:22:22.000Z" title="发表于 2023-07-06 22:22:22">2023-07-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/07/06/%E5%90%8E%E7%AB%AF%E8%A7%84%E5%88%92/" title="Java后端"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/javahd.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java后端"/></a><div class="content"><a class="title" href="/2023/07/06/%E5%90%8E%E7%AB%AF%E8%A7%84%E5%88%92/" title="Java后端">Java后端</a><time datetime="2023-07-06T14:22:22.000Z" title="发表于 2023-07-06 22:22:22">2023-07-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/06/02/MybatisPlus/" title="MybatisPlus"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/mybatisplus.svg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MybatisPlus"/></a><div class="content"><a class="title" href="/2023/06/02/MybatisPlus/" title="MybatisPlus">MybatisPlus</a><time datetime="2023-06-02T14:22:22.000Z" title="发表于 2023-06-02 22:22:22">2023-06-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/05/05/Linux/" title="Linux"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/Linux.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Linux"/></a><div class="content"><a class="title" href="/2023/05/05/Linux/" title="Linux">Linux</a><time datetime="2023-05-05T14:22:22.000Z" title="发表于 2023-05-05 22:22:22">2023-05-05</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/05/05/Redis/" title="Redis"><img src= "" data-lazy-src="/img/loading.gif" data-original="ttps://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/Redis.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis"/></a><div class="content"><a class="title" href="/2023/05/05/Redis/" title="Redis">Redis</a><time datetime="2023-05-05T14:22:22.000Z" title="发表于 2023-05-05 22:22:22">2023-05-05</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By 辰</div><div class="framework-info"><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn">粤ICP备2023096650号</a><span class="footer-separator">|</span><a target="_blank" rel="noopener" href="http://hchen.cloud">hchen.cloud</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><div class="js-pjax"></div><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div>
        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var e=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,c=a();function a(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(){e&&(c=a());for(var t,o=0;o<c.length;o++)0<=(t=(t=c[o]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,n,a,i=c[o];e=function(){c=c.filter(function(t){return i!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(i)},(t=i).hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(n=new Image,a=t.getAttribute("data-original"),n.onload=function(){t.src=a,t.removeAttribute("data-original"),e&&e()},t.src!==a&&(n.src=a))}()}function i(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",i),r.addEventListener("resize",i),r.addEventListener("orientationchange",i)}(this);</script></body></html>